﻿#include "../../includes/network/cudpsocket.h"
#include "../../includes/QsLog/QsLog.h"

CUdpSocket::CUdpSocket(QObject *parent)
    : m_isProcessDatagramHearder(false)
{
    connect(&m_UdpSocket,&QUdpSocket::readyRead,this,&CUdpSocket::reciverPendingDatagram);
}

CUdpSocket::~CUdpSocket(void)
{

}

/**
 * @brief Open 开始指定端口开始侦听
 * @param port 要打开的端口
 * @return 如果端口打开成功返回真，否则返回假
 */
bool CUdpSocket::Open(int port)
{
    return m_UdpSocket.bind(port,QUdpSocket::ShareAddress);
}

/**
 * @brief CUdpSocket::Send 发送报文
 * @param Datagramdata 要发送的报文数据
 * @param type 发送类型：单播，广播，组播
 * @param port 要接收数据的端口
 * @return 返回发送成功的数据长度
 */
qint64 CUdpSocket::Send(QByteArray Datagramdata,int port,QHostAddress type)
{
    if(Datagramdata.isEmpty())
        return -1;

    QByteArray pSendDatagramData;

    tagDatagramHearder ptagDatagramHearder;
    ptagDatagramHearder.version = 100;
    ptagDatagramHearder.size = Datagramdata.size();

    pSendDatagramData.append((char*)&ptagDatagramHearder,sizeof(tagDatagramHearder));
    pSendDatagramData.append(Datagramdata);

    return m_UdpSocket.writeDatagram(pSendDatagramData.data(),pSendDatagramData.size(),type,port);
}


void CUdpSocket::reciverPendingDatagram()
{
    while(m_UdpSocket.hasPendingDatagrams())
    {
        QByteArray preciverDatagramData;

        preciverDatagramData.resize(m_UdpSocket.pendingDatagramSize());

        if(m_UdpSocket.readDatagram(preciverDatagramData.data(),preciverDatagramData.size()) > 0)
            m_datagramData.append(preciverDatagramData);
    }

    while(!m_datagramData.isEmpty())
    {
        if(!m_isProcessDatagramHearder && m_datagramData.size() > sizeof(tagDatagramHearder))
        {
            memcpy(&m_DatagramHearder,m_datagramData.constData(),sizeof(tagDatagramHearder));

            if(m_DatagramHearder.version != 100)
            {
                QLOG_ERROR()<<"CUdpSocket::reciverPendingDatagram:"<<" version is error.";
                return;
            }

            m_datagramData.remove(0,sizeof(tagDatagramHearder));
            m_isProcessDatagramHearder = true;
        }

        if(!m_isProcessDatagramHearder || m_datagramData.size() < m_DatagramHearder.size)
            break;

        // 得到当前文件数据
        QByteArray precvDatagramData = m_datagramData.mid(0,m_DatagramHearder.size);
        m_datagramData.remove(0,m_DatagramHearder.size);

        emit processPendingDatagram(precvDatagramData);

        m_isProcessDatagramHearder=false;
    }
}
